package com.haitaoit.chengquan.module.home.activity.forum;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.home.adapter.forum.ImageAdapter;
import com.haitaoit.chengquan.module.home.model.TitleModel;
import com.haitaoit.chengquan.module.login.LoginActivity;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DialogUtil;
import com.haitaoit.chengquan.utils.GetPhotoListener;
import com.haitaoit.chengquan.utils.GetPhotoOrImage;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.Img;
import com.haitaoit.chengquan.view.MyGridView;
import com.haitaoit.chengquan.view.pickerview.OptionsPopupWindow;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class PostForumActivity extends BaseActivity {
    @ViewInject(R.id.forum_type)
    TextView forum_type;
    @ViewInject(R.id.add_forum_img)
    MyGridView add_forum_img;
    @ViewInject(R.id.add_forum_title)
    EditText add_forum_title;
    @ViewInject(R.id.add_forum_content)
    EditText add_forum_content;


    private ImageAdapter adapter;
    private GetPhotoOrImage getPhotoOrImage;
    private int change = 0;
    private List<TitleModel> listTitle;
    private String id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_post_forum);
        setTitle_V("发表帖子");
        setLeftShow(1, R.mipmap.left);
        backLeft_V();
        ViewUtils.inject(this);

        Intent intent = getIntent();
        String titleName = intent.getStringExtra("typeName");

        if (titleName!=null) {
            forum_type.setText(titleName);
        }
        adapter = new ImageAdapter(this);
        adapter.setBackCall(backCall);
        add_forum_img.setAdapter(adapter);
        getPhotoOrImage = new GetPhotoOrImage(this);
        httpGetesther_class_list();
    }

    @OnClick({R.id.forum_type, R.id.add_forum_post,})
    public void onClick(View v) {
        // 收起键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        switch (v.getId()) {
            case R.id.forum_type:// 分类
                updateBigtype(listTitle);
                break;
            case R.id.add_forum_post:// 发布
                if (PreferenceUtils.getPrefString("user_id", "").equals("")) {
                    Intent intent = new Intent(this, LoginActivity.class);
                    intent.putExtra("tag", "0");
                    startActivity(intent);
                } else if (forum_type.getText().toString().equals("选择分类")) {
                    ToastUtils.showToast("请选择分类！");
                } else if (add_forum_title.getText().toString().equals("")) {
                    ToastUtils.showToast("请输入标题！");
                } else if (add_forum_content.getText().toString().equals("")) {
                    ToastUtils.showToast("请输入内容！");
                } else {
                    httpadd_esther();
                }
                break;
        }
        super.onClick(v);
    }

    private void httpadd_esther() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        String sign = GetSign.genPackageSign(list);

        String url = Constant.add_esther + "id=0&user_id=" +
                PreferenceUtils.getPrefString("user_id", "") + "&sign=" + sign;
        JSONObject params = new JSONObject();
        try {
            params.put("esther_class_id", id);
            params.put("title", add_forum_title.getText().toString());
            params.put("content", add_forum_content.getText().toString());
            JSONArray house_imgs = new JSONArray();
            for (int i = 0; i < adapter.getList().size(); i++) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("img_url", adapter.getList().get(i).getImg());
                house_imgs.put(jsonObject);
            }
            params.put("img_list", house_imgs);
        } catch (JSONException e1) {
            e1.printStackTrace();
        }

        HttpUtilsSingle.doPost(this, true, url, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            break;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
//                            setResult(1);
                            finish();
                            break;
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    private void httpGetesther_class_list() {

        int i = (int) Math.floor(Math.random() * 9000 + 1000);
        final List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("rnd", i + ""));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("rnd", i + "");
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getesther_class_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            listTitle = gson.fromJson(Response,
                                    new TypeToken<List<TitleModel>>() {
                                    }.getType());
                            return;
                        case 2:// 暂无内容
                            ToastUtils.showToast(Errmsg);
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    private void updateBigtype(final List<TitleModel> list) {
        final ArrayList<String> list2 = new ArrayList<String>();
        for (int i = 0; i < list.size(); i++) {
            list2.add(list.get(i).getName());
        }

        OptionsPopupWindow popSex = new OptionsPopupWindow(this, "");
        popSex.setPicker(list2);
        popSex.setSelectOptions(0);
        popSex.setOnoptionsSelectListener(new OptionsPopupWindow.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                forum_type.setText(list2.get(options1));
                id = list.get(options1).getId();
            }
        });
        popSex.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);// popupwindow消失的时候恢复成原来的透明度
            }
        });
        popSex.showAtLocation(forum_type, Gravity.BOTTOM, 0, 0);
        backgroundAlpha(0.6f);
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;// 0.0-1.0
        getWindow().setAttributes(lp);
    }

    BackCall backCall = new BackCall() {
        @Override
        public void deal(int which, Object... obj) {
            int position = (Integer) obj[0];
            switch (which) {
                case R.id.icon:
                    if (position == adapter.getList().size()) {
                        getPhotoOrImage.setGetPhotoListener(getPhoto1);
                        getPhotoOrImage.getImage();
                    } else {
                        Dialog dlg = DialogUtil.ShowTop(PostForumActivity.this, new BackCall() {
                            @Override
                            public void deal(int which, Object... obj) {
                                switch (which) {
                                    case R.id.tv_photos:// 图库
                                        getPhotoOrImage.setGetPhotoListener(getPhoto);
                                        getPhotoOrImage.getImage();
                                        break;
                                    case R.id.tv_camera:
                                        List<Img> list = adapter.getList();
                                        list.remove(change);
                                        adapter.setList(list);
                                        adapter.notifyDataSetChanged();
                                        break;
                                }
                                super.deal(which, obj);
                            }
                        });
                        dlg.setCanceledOnTouchOutside(true);
                        dlg.show();

                        DisplayMetrics metric = new DisplayMetrics();
                        PostForumActivity.this.getWindowManager().getDefaultDisplay().getMetrics(metric);
                        int width = metric.widthPixels; // 屏幕宽度（像素）
                        WindowManager.LayoutParams params = dlg.getWindow().getAttributes();
                        params.width = width;
                        params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
                        dlg.getWindow().setAttributes(params);
                    }
                    break;
            }
            super.deal(which, obj);
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getPhotoOrImage.onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    // 处理调用相机或者相册的图片回调
    GetPhotoListener getPhoto = new GetPhotoListener() {
        @Override
        public void completeGetImage(String file, Bitmap upbitmap) {
            Img img = new Img();
            img.setBmp(upbitmap);
            img.setImg(file);
            List<Img> imgs = adapter.getList();
            imgs.set(change, img);
            adapter.setList(imgs);
            adapter.notifyDataSetChanged();
        }
    };

    // 处理调用相机或者相册的图片回调
    GetPhotoListener getPhoto1 = new GetPhotoListener() {
        @Override
        public void completeGetImage(String file, Bitmap upbitmap) {
            Img img = new Img();
            img.setBmp(upbitmap);
            img.setImg(file);
            List<Img> imgs = adapter.getList();
            imgs.add(img);
            adapter.setList(imgs);
            adapter.notifyDataSetChanged();
        }
    };
}
